import React, { useRef, useEffect, useState } from "react";
import { Card, Avatar, Button, Divider, Menu, Dropdown, message } from "antd";
import { EditOutlined, UserOutlined } from "@ant-design/icons";
import { uploadAvatarApi } from "../../../api/user";
import { useStore } from "../../../stores/store.jsx"; // 引入 useStore
import { useNavigate } from "react-router-dom";

const MyProfile = () => {
  const inputRef = useRef(null);
  const { state, getUserInfo } = useStore(); // 从 store 中获取 state 和 getUserInfo 方法
  const [avatarUrl, setAvatarUrl] = useState(() => {
    if (state.userInfo?.avatar) {
      return `${import.meta.env.VITE_APP_MEDIA_URL}/${state.userInfo.avatar}`;
    }
    return null;
  });
  const [loading, setLoading] = useState(false);
  const [previewUrl, setPreviewUrl] = useState(null);
  const navigate = useNavigate();

  const handleMenuClick = ({ key }) => {
    if (key === "upload_avatar") {
      // 触发文件选择
      inputRef.current.click();
    }
  };

  useEffect(() => {
    if (state.userInfo?.avatar) {
      const timestamp = new Date().getTime();
      setAvatarUrl(
        `${import.meta.env.VITE_APP_MEDIA_URL}/${
          state.userInfo.avatar
        }?t=${timestamp}`
      );
    }
  }, [state.userInfo]);

  const handleFileChange = async (event) => {
    const file = event.target.files[0];
    if (file) {
      setLoading(true);
      // 立即显示本地预览
      const localUrl = URL.createObjectURL(file);
      setPreviewUrl(localUrl);

      const formData = new FormData();
      formData.append("file", file);

      try {
        const uploadResult = await uploadAvatarApi(formData);
        await getUserInfo(true);

        // 清理本地预览
        URL.revokeObjectURL(localUrl);
        setPreviewUrl(null);

        // 更新头像URL
        const timestamp = Date.now();
        setAvatarUrl(
          `${import.meta.env.VITE_APP_MEDIA_URL}/${
            state.userInfo.avatar
          }?t=${timestamp}`
        );
        message.success("头像上传成功");
      } catch (err) {
        console.error(err);
        message.error("头像上传失败，请重试");
        // 清理本地预览
        URL.revokeObjectURL(localUrl);
        setPreviewUrl(null);
      } finally {
        setLoading(false);
      }
    }
  };

  const handleEditResume = () => {
    navigate("/home/resume");
  };

  const menuItems = [{ label: "上传头像", key: "upload_avatar" }];

  const menu = <Menu items={menuItems} onClick={handleMenuClick} />;

  return (
    <Card
      style={{
        borderRadius: "8px",
        boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
        maxWidth: "300px",
      }}
    >
      {/* 个人信息 */}
      <div style={{ textAlign: "center" }}>
        <Dropdown overlay={menu} trigger={["contextMenu"]}>
          <div>
            <Avatar
              size={64}
              src={previewUrl || avatarUrl}
              alt="User Avatar"
              style={{ cursor: "pointer" }}
              icon={!avatarUrl && !previewUrl && <UserOutlined />}
            />
          </div>
        </Dropdown>
        <h3 style={{ margin: 0 }}>{state.userInfo?.username}</h3>{" "}
        {/* 从 store 中获取用户名 */}
        <p style={{ color: "#888", margin: "4px 0" }}>简历完整度 70%</p>
        <Button
          type="primary"
          icon={<EditOutlined />}
          size="small"
          onClick={handleEditResume}
        >
          编辑简历
        </Button>
      </div>

      <Divider />

      {/* 数据统计 */}
      <div style={{ display: "flex", justifyContent: "space-around" }}>
        <div style={{ textAlign: "center" }}>
          <h4 style={{ margin: 0 }}>9</h4>
          <p style={{ color: "#888", margin: 0 }}>谁看过我</p>
        </div>
        <div style={{ textAlign: "center" }}>
          <h4 style={{ margin: 0 }}>0</h4>
          <p style={{ color: "#888", margin: 0 }}>我的投递</p>
        </div>
        <div style={{ textAlign: "center" }}>
          <h4 style={{ margin: 0 }}>0</h4>
          <p style={{ color: "#888", margin: 0 }}>我的收藏</p>
        </div>
      </div>

      <Divider />

      {/* 功能模块 */}
      <div>
        <p style={{ margin: "8px 0", fontWeight: "bold" }}>功能模块</p>
        <ul style={{ padding: 0, listStyle: "none" }}>
          <li style={{ marginBottom: "8px" }}>
            <Button type="link" block>
              附件简历
            </Button>
          </li>
          <li style={{ marginBottom: "8px" }}>
            <Button type="link" block>
              刷新简历
            </Button>
          </li>
          <li style={{ marginBottom: "8px" }}>
            <Button type="link" block>
              金卡服务
            </Button>
          </li>
          <li style={{ marginBottom: "8px" }}>
            <Button type="link" block>
              简历诊断
            </Button>
          </li>
        </ul>
      </div>

      {/* 文件输入，设置为不可见 */}
      <input
        type="file"
        ref={inputRef}
        style={{ display: "none" }}
        accept="image/*"
        onChange={handleFileChange}
      />
    </Card>
  );
};

export default MyProfile;
